package club.gskj.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userinfo")
    public String userInfo(@RequestParam("token") String token) {
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String redirectUrl, Model model,
                            @CookieValue(value = "sso_token", required = false) String token) {
        // 判断当前登录是否已携带上次 登陆过返回的cookie信息。
        if (!StringUtils.isEmpty(token)) {
            // 如果有cookie。说明已经在sso-server登陆过。直接返回 redirectUrl地址。并携带token值
            return "redirect:" + redirectUrl + "?token=" + token;
        }
        model.addAttribute("redirectUrl", redirectUrl);
        return "login";
    }

    @PostMapping("/dologin")
    public String doLogin(String username, String password, String redirectUrl
            , HttpServletResponse response) {
        // 登陆成功。跳转到之前的页面
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            // 登陆成功跳转到 用户列表
            String key = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(key, username);

            // 把登陆成功的用户存储
            redirectUrl += "?token=" + key;
            // 响应cookie到浏览器
            response.addCookie(new Cookie("sso_token", key));
            return "redirect:" + redirectUrl;
        }
        // 登陆失败，跳回登录页
        return "login";
    }
}
